package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.zhentao.pojo.Role;
import com.zhentao.pojo.User;
import com.zhentao.service.RoleService;
import com.zhentao.service.UserService;
import com.zhentao.util.JwtService;
import com.zhentao.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private DefaultKaptcha captchaProducer;

/**
 * 登录方法
  */

    @RequestMapping("login")
    public Result login(@RequestBody User user){
        // 1. 先根据用户名查数据库用户（只查用户名，不查密码）
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", user.getName());
        User dbUser = userService.getOne(queryWrapper);

        // 用户关联角色
        if (dbUser != null) {
            Role byId = roleService.getById(dbUser.getRid());
            System.err.println(byId);
            dbUser.setRname(byId.getName());
        }

        // 2. 校验用户是否存在 + 密码是否匹配
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (dbUser != null && encoder.matches(user.getPassword(), dbUser.getPassword())) {
            // 修改最后登录的时间
            dbUser.setLastLoginTime(new Date());
            userService.updateById(dbUser);
            System.err.println(dbUser);

            // 3. 生成 JWT（若需要，结合用户信息生成）
            Map<String, Object> map = new HashMap<>();
            map.put("id", dbUser.getId());
            map.put("name", dbUser.getName());
            String jwt = JwtService.createToken(map);

            return Result.OK(jwt);
        } else {
            return Result.ERROR("登录失败");
        }
    }


    /**
     * @throws Exception
     * 生成验证码
     */
    @RequestMapping("/common/kaptcha")
    public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        byte[] captchaOutputStream = null;
        ByteArrayOutputStream imgOutputStream = new ByteArrayOutputStream();
        try {
            //生产验证码字符串并保存到session中
            String verifyCode = captchaProducer.createText();
            httpServletRequest.getSession().setAttribute("verifyCode", verifyCode);
            BufferedImage challenge = captchaProducer.createImage(verifyCode);
            ImageIO.write(challenge, "jpg", imgOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        captchaOutputStream = imgOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaOutputStream);
        responseOutputStream.flush();
        responseOutputStream.close();
    }


/**
 * 验证输入的验证码与生成的验证码是否匹配
  */

    @RequestMapping("/verifyCaptcha")
    public ResponseEntity<?> verifyCaptcha(HttpServletRequest request, @RequestParam String userCaptcha) {
        // 从session中获取正确的验证码
        String sessionCaptcha = (String) request.getSession().getAttribute("verifyCode");

        if (sessionCaptcha == null) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("验证码已过期");
        }

        // 比较用户输入的验证码和session中的验证码
        if (sessionCaptcha.equalsIgnoreCase(userCaptcha)) {
            // 验证成功后清除session中的验证码，防止重复使用
            request.getSession().removeAttribute("verifyCode");
            System.err.println("验证码正确");
            return ResponseEntity.ok().body("验证码正确");
        } else {
            System.err.println("验证码错误");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("验证码错误");
        }
    }
    /**
     * 添加用户
     */
    @RequestMapping("insert")
    public Result insert(@RequestBody User user){
        user.setLastLoginTime(new Date());
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        //修改密码后对其进行MD5加盐加密
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encode = encoder.encode(user.getPassword());
        user.setPassword(encode);
        userService.save(user);
        return Result.OK("用户添加成功");
    }
/**
 * 对密码进行修改
  */

    @RequestMapping("updatePassword")
    public Result updatePassword(@RequestBody User user){
        //修改密码后对其进行MD5加盐加密
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encode = encoder.encode(user.getPassword());
        user.setPassword(encode);
        userService.updateById(user);
        return Result.OK("用户密码修改成功");
    }
}
